import { get, post } from '@common/ajax';
import { SHOP_URL, MARKET_URL, MEMBER_URL, INVENTORY_URL } from '@common/url';
import { MARKET_ISSUER, MARKET_SCENE } from '@constants/market';
import { DELIVERY_TYPE } from '@constants/shop';
import { calcReviewOrderPrice, changeReviewItemRemark, changeReviewItemUseCoupon, dealCombinedOrderParam, reviewListAddCoupon, reviewListAddDiscountInfo, reviewListToMarketList } from '@biztools/review';
import logger from '@common/logger';
import {
    SET_ORDER_REVIEW_LIST,
    GET_ORDER_REQUEST_ID,
    GET_MEMBER_CARD_INFO,
    CHANGE_DELIVERY_TYPE,
    CHANGE_BOOK_DAYS,
    CHANGE_DELIVERY_ADDRESS,
    SET_ORDER_REVIEW_DISCOUNT_INFO,
    CALC_REVIEW_ORDER_PRICE,
    CHANGE_CARD_PAY_FLAG,
    SET_CARD_DISCOUNT_INFO,
} from '@store/mutationType';
import { dealCouponItem } from '@biztools/market';
import { getBrandIdCookie, getUserMemberIdCookie } from '@biztools/info';
import { autoShopPayment } from '@common/environment';
import { repalceTo } from '@common/utils';
import { PAY_ORDER_STATUS } from '@constants/pay';
import { TipError } from '@common/tip';

const review = {
    state: {
        orderReviewList: [],
        orderRequestId: '',
        addressInfo: null, // 地址信息
        deliveryType: DELIVERY_TYPE.EXPRESS, // 配送方式
        memberCardInfo: null, // 会员卡信息
        discountInfo: null,
        cardDiscountInfo: null,
        totalPrice: 0,
        totalDiscountPrice: 0,
        isCardPay: false,
        isCanCreateOrder: true,
        bookDays: null,
    },
    mutations: {
        SET_ORDER_REVIEW_LIST: (state, orderReviewList) => {
            Object.assign(state, { orderReviewList });
        },
        GET_ORDER_REQUEST_ID: (state, orderRequestId) => {
            Object.assign(state, { orderRequestId });
        },
        GET_MEMBER_CARD_INFO: (state, memberCardInfo) => {
            Object.assign(state, { memberCardInfo });
        },
        CHANGE_DELIVERY_TYPE: (state, deliveryType) => {
            Object.assign(state, { deliveryType });
        },
        CHANGE_DELIVERY_ADDRESS: (state, addressInfo) => {
            Object.assign(state, { addressInfo });
        },
        SET_ORDER_REVIEW_DISCOUNT_INFO: (state, discountInfo) => {
            Object.assign(state, { discountInfo });
        },
        CALC_REVIEW_ORDER_PRICE: (state, { totalPrice, totalDiscountPrice }) => {
            Object.assign(state, {
                totalPrice,
                totalDiscountPrice,
            });
        },
        CHANGE_CARD_PAY_FLAG: (state, isCardPay) => {
            Object.assign(state, { isCardPay });
        },
        SET_CARD_DISCOUNT_INFO: (state, cardDiscountInfo) => {
            Object.assign(state, { cardDiscountInfo });
        },
        CHANGE_BOOK_DAYS: (state, bookDays) => {
            Object.assign(state, { bookDays });
        },
    },
    actions: {
        // 获取订单唯一 RequestId
        getOrderRequestId: async ({ commit }) => {
            const res = await get(SHOP_URL.requestId);
            logger.success('Review => 获取的RequestId为', res.request_id);
            commit(GET_ORDER_REQUEST_ID, res.request_id);
        },
        // 清除 RequestId
        clearOrderRequestId: ({ commit }) => {
            commit(GET_ORDER_REQUEST_ID, '');
        },
        // 设置订单数据
        setOrderReviewList: ({ commit, dispatch }, list) => {
            logger.debugger('Review => 设置确认订单信息', list);
            commit(SET_ORDER_REVIEW_LIST, list);
        },
        // 获取订单可用的优惠券
        getOrderReviewCoupon: async ({ commit, state }) => {
            const { orderReviewList } = state;
            const res = await get(MARKET_URL.avaliable, {
                use_scene: MARKET_SCENE.order,
                with_item_category_confs: false,
                with_item_confs: true,
            });
            logger.debugger('Review => 获取可用优惠券', res);
            const couponList = (res.data.member_coupons || []).map(item => dealCouponItem(item));
            // 订单数据中添加可用的优惠券等信息
            const list = reviewListAddCoupon(orderReviewList, couponList);
            commit(SET_ORDER_REVIEW_LIST, list);
        },
        // 获取会员卡信息
        getMemberCardInfo: async ({ commit }) => {
            const res = await get(MEMBER_URL.account);
            if (res.data) {
                const accountInfo = res.data;
                let market;
                try {
                    market = await get(MARKET_URL.cardDiscount(accountInfo.card_id));
                } catch (error) {
                    market = false;
                }
                const discountInfo = market ? market.data.card_discount : { discount: 100 };
                commit(GET_MEMBER_CARD_INFO, {
                    id: accountInfo.card_id,
                    accId: accountInfo.acc_id,
                    balance: accountInfo.balance,
                    discount: discountInfo.discount / 10,
                    cardName: accountInfo.card_name,
                    integral: accountInfo.integral,
                    integralUp: accountInfo.unit_integral_amount,
                    rechargeUp: accountInfo.topup_limit,
                    canRecharge: accountInfo.can_recharge,
                    cover: accountInfo.cover,
                });
            }
        },
        // 订单优惠试算
        dealOrderMarket: async ({ commit, state, dispatch }) => {
            const { orderRequestId, memberCardInfo, orderReviewList } = state;
            if (!orderRequestId) {
                setTimeout(() => {
                    dispatch('dealOrderMarket');
                }, 200);
                return;
            }
            try {
                const res = await post(MARKET_URL.calc, {
                    out_trans_no: orderRequestId,
                    trial_scene: MARKET_SCENE.order,
                    trial_issuer: MARKET_ISSUER.emall,
                    out_card_id: memberCardInfo ? memberCardInfo.id : 0,
                    trial_owners: reviewListToMarketList(orderReviewList),
                });
                const list = reviewListAddDiscountInfo(orderReviewList, res.data);
                commit(SET_ORDER_REVIEW_LIST, list);
                commit(SET_ORDER_REVIEW_DISCOUNT_INFO, res);
                commit(SET_CARD_DISCOUNT_INFO, res.data.card_discount);
                dispatch('calcOrderPrice');
            } catch (error) {
                dispatch('calcOrderPrice');
            }
        },
        // 计算订单价格，单个订单&总订单
        calcOrderPrice: ({ state, commit }) => {
            const { orderReviewList, deliveryType, cardDiscountInfo } = state;
            logger.debugger('Review => 配送方式', deliveryType);
            logger.info('Review => 计算价格列表', orderReviewList);
            const { list, totalPrice, totalDiscountPrice } = calcReviewOrderPrice(orderReviewList, deliveryType);
            logger.info('Review => 卡优惠为', cardDiscountInfo);
            let _totalPrice = cardDiscountInfo ? totalPrice - cardDiscountInfo.off : totalPrice;
            let _totalDiscountPrice = cardDiscountInfo ? totalDiscountPrice + cardDiscountInfo.off : totalDiscountPrice;
            commit(SET_ORDER_REVIEW_LIST, list);
            commit(CALC_REVIEW_ORDER_PRICE, { totalPrice: _totalPrice, totalDiscountPrice: _totalDiscountPrice });
        },
        // 修改订单备注
        changeOrderReviewItemRemark: ({ commit, state }, { id, remark }) => {
            const { orderReviewList } = state;
            const list = changeReviewItemRemark(orderReviewList, id, remark);
            commit(SET_ORDER_REVIEW_LIST, list);
        },
        // 修改订单使用优惠券
        changeOrderReviewItemCoupon: ({ commit, state, dispatch }, { id, useCoupon }) => {
            const { orderReviewList } = state;
            const list = changeReviewItemUseCoupon(orderReviewList, id, useCoupon);
            commit(SET_ORDER_REVIEW_LIST, list);
            dispatch('dealOrderMarket');
        },
        // 修改配送方式
        changeOrderReviewDeliveryType: ({ commit, dispatch }, deliveryType) => {
            commit(CHANGE_DELIVERY_TYPE, deliveryType);
            dispatch('matchReviewListWarehouseInfo');
        },
        // 修改预约时间
        changeOrderReviewBookDays: ({ commit }, bookDays) => {
            commit(CHANGE_BOOK_DAYS, bookDays);
        },
        // 修改收货地址
        changeOrderReivewAddress: ({ commit, dispatch }, addressInfo) => {
            commit(CHANGE_DELIVERY_ADDRESS, addressInfo);
            dispatch('matchReviewListWarehouseInfo');
        },
        // 匹配仓库
        matchReviewListWarehouseInfo: async ({ commit, state, dispatch }) => {
            const { orderReviewList, addressInfo, deliveryType } = state;
            let list = [];
            for (let i = 0; i < orderReviewList.length; i++) {
                const warehouseInfo = await get(INVENTORY_URL.matchWarehouse, {
                    lat: addressInfo.latitude,
                    lng: addressInfo.longitude,
                    city_code: addressInfo.city_code,
                    store_id: orderReviewList[i].id,
                    deliver_type: deliveryType,
                });
                logger.debugger('Review => 匹配仓库', warehouseInfo);
                list.push({
                    ...orderReviewList[i],
                    warehouseInfo,
                });
            }
            commit(SET_ORDER_REVIEW_LIST, list);
            dispatch('calcOrderPrice');
        },
        // 切换是否卡支付
        changeCardPayFlag: ({ commit }, flag) => {
            commit(CHANGE_CARD_PAY_FLAG, flag);
        },
        // 组合下单
        createCombinedOrder: async ({ state, dispatch }) => {
            const { orderRequestId, addressInfo, orderReviewList, deliveryType, cardDiscountInfo,
                memberCardInfo, isCardPay, bookDays } = state;
            const orders = dealCombinedOrderParam(orderReviewList, deliveryType,
                cardDiscountInfo && cardDiscountInfo.off || 0, bookDays);
            logger.debugger('Review => 处理的订单数据为：', orders);
            logger.debugger('Review => 处理的订单数据为：', orders);
            const param = {
                request_id: orderRequestId,
                address_info: {
                    lat: addressInfo.latitude,
                    lng: addressInfo.longitude,
                    city_code: addressInfo.city_code,
                    contact: addressInfo.contact_name,
                    mobile: addressInfo.contact_mobile,
                    address: addressInfo.address,
                },
                orders,
                card_info: {
                    brand_id: getBrandIdCookie(),
                    card_id: memberCardInfo? memberCardInfo.id : 0,
                    member_id: getUserMemberIdCookie(),
                    acc_id: memberCardInfo ? memberCardInfo.accId : 0,
                },
                balance_pay: isCardPay,
            };
            const res = await post(SHOP_URL.orderCreate, param);
            logger.success('Review => 下单结果', res);
            if (res) {
                return res.status;
            } else {
                dispatch('getOrderRequestId');
                setTimeout(() => {
                    dispatch('dealOrderMarket');
                }, 300);
            }
        },
        payCombinedOrder: async ({ state }) => {
            const { orderRequestId, isCardPay } = state;
            const res = await post(SHOP_URL.orderPay, {
                request_id: orderRequestId,
                balance_pay: isCardPay,
            });
            logger.success('Review => 支付结果', res);
            switch(res.status) {
            case PAY_ORDER_STATUS.init:
                // 执行平台相关支付
                autoShopPayment(res.prepay_info, '', () => {});
                break;
            case PAY_ORDER_STATUS.success:
                // 支付成功，直接跳转到订单列表
                repalceTo('shop-order/list');
                break;
            case PAY_ORDER_STATUS.failed:
                TipError('支付失败，请重试');
                repalceTo('shop-order/list');
                break;
            case PAY_ORDER_STATUS.close:
                TipError('支付已关闭');
                repalceTo('shop-order/list');
                break;
            }
        },
    },
};

export default review;
